/**
 * Created by qinrui on 2017/11/10
 * 人事简报
 */

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { WhiteSpace } from "@ali/ding-ui";
import './index.less';

import { Icon } from "@ali/ding-ui";

//components
import CardHeader from '../../components/CardHeader';
import SmartStackWS from "../../components/LineChart/smartStackWS.jsx"
import SmartPie from "../../components/LineChart/smartPie.jsx";
import HelpModal from "../../components/HelpModal/index";

// actions
import {fetchGetOnJobDataAnalysis } from '../../actions/weekly';

// utils
import { get } from "../../utils/db";
import { departmentsPicker, alert, setTitle, setRight, openLink } from "../../utils/dingtalk.js";

// 将store注入组件的props
const mapStateToProps = state => ({});
// 将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
    //区分绑定到props的action与传递的props
    actions: bindActionCreators(
        {
            dispatch,
            fetchGetOnJobDataAnalysis
        },
        dispatch
    )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class MainpowerReportDetail extends Component {
    constructor (props) {
        super(props);
        this.state = {
            deptsName: "全部",
            deptsId: [],
            isScrollIntoView: true,
            isLoading: true
        }
        setRight({
            show:false
        })
        setTitle({
            title: "在职员工分析"
        });

    }

    componentWillMount (){
        // 在职员工分析
        this.getOnJobDataAnalysis();
    }

    componentDidUpdate() {
        const anchor = this.props.location.query.anchor;
        if(this.refs[anchor] && this.state.isScrollIntoView){
            this.refs[anchor].scrollIntoView();
        }
    }

    /**
     * 在职员工分析
     */
    getOnJobDataAnalysis = (params) => {
        let dataAnalysis = [];
        this.props.actions.fetchGetOnJobDataAnalysis(params)
            .then((res) => {
                if(res.success){
                    const { accessDepts=[], totalEmpNum, corpAgeData, empAgeData, empEduData, empTypeData, genderData, marriedData } = res.result;
                    dataAnalysis.push(
                        {
                            name: "员工类型构成",
                            type: "empTypeData",
                            data: empTypeData
                        },
                        {
                            name: "司龄分布",
                            type: "corpAgeData",
                            data: corpAgeData
                        },
                        {
                            name: "学历分布",
                            type: "empEduData",
                            data: empEduData
                        },
                        {
                            name: "年龄分布",
                            type: "empAgeData",
                            data: empAgeData
                        },
                        {
                            name: "性别比例",
                            type: "genderData",
                            data: genderData
                        },
                        {
                            name: "已婚比例",
                            type: "marriedData",
                            data: marriedData
                        }
                    );
                    
                    let deptsId = "",
                        deptsName = "";
                    
                    if(accessDepts.length){
                        for(let i=0; i<accessDepts.length; i++){
                            if(i<accessDepts.length-1){
                                deptsId += accessDepts[i].deptId + ",";
                                deptsName += accessDepts[i].deptName + "、";
                            } else {
                                deptsId += accessDepts[i].deptId;
                                deptsName += accessDepts[i].deptName;
                            }
                        }
                        deptsId = accessDepts[0].deptId ===-1 ? "" : deptsId;
                    } else {
                        deptsName = "无"
                    }

                    this.setState({
                        deptsId,
                        pickedDeptsId: accessDepts.map(item => item.deptId),
                        deptsName,
                        pickedDeptsName: accessDepts.map(item => item.deptName),
                        totalEmpNum,
                        dataAnalysis,
                        isLoading: false
                    })
                }
            });
    }

    /**
     * 取图表数据
     */
    getCharData = (data) => {
        const charData = [];

        for(let i=0; i< data.length; i++){
            if(data.length > 3){
                charData.push(
                    { "yAxisData": data[i].typeNum, "xAxisData": data[i].typeName, "name": data[i].typeName}
                )
            } else {
                let typeNum = data[i].typeNum / this.state.totalEmpNum
                charData.push(
                    {a: '1', b: Number(typeNum.toFixed(2)), c: data[i].typeName,d:data[i].typeNum}
                )
            }
        }
        
        return charData;
    }
    
    handleDept =() => {
        window._rlog(`_empanalyzedetail_select_depts`);

        const corpId = get("corpId");
        const { deptsId, pickedDeptsId } = this.state;
        
        departmentsPicker({
            title: "请选择部门",
            multiple: true, // 多选
            pickedDepartments: pickedDeptsId || [], // 已选部门
            maxDepartments: 100, // 最大部门数
            corpId,
            appId: 158,
            cb: result => {
                let { departments } = result;
                departments.sort((a, b) => a.id - b.id);

                let deptsId ="";
                let deptsName ="";

                for(let i=0; i<departments.length; i++){
                    if(i<departments.length-1){
                        deptsId += departments[i].id+ ","
                        deptsName += departments[i].name+ ","
                    } else {
                        deptsId += departments[i].id
                        deptsName += departments[i].name
                    }
                }

                this.setState({
                    deptsId,
                    pickedDeptsId: departments.map(item => item.deptId),
                    deptsName,
                    isScrollIntoView: false
                });

                this.getOnJobDataAnalysis({depts: deptsId});
            },
            errCb: err => {
                alert({ title: "出错了", message: JSON.stringify(err) })
            }
          });
      }
    
    render(){
        const { isLoading, deptsId, deptsName, pickedDeptsName, totalEmpNum, dataAnalysis=[] } = this.state;
        return (
            <div className="manpower-Report-detail">
                {
                    !isLoading &&
                    <div>
                        <div className="hackIos11ScrollBug">
                            <div className="hackIos11ScrollBugContent">
                            　   _
                            </div>
                        </div>
                        <div ref="handleDept" className="manpower-Report-detail-header line">
                            <div className="title">查看范围</div>
                            <div className="value" 
                                onClick={
                                    this.handleDept
                                }>
                                <Icon type="right" size="md" className="roster-arrow" />
                                <div className="depts-warp">
                                    <span className="depts-name">{deptsName}</span>
                                </div>
                            </div>
                        </div>
                        <div className="manpower-Report-detail-header">
                            <div className="title">在职员工</div>
                            <div className="value"
                                onClick={ 
                                    () => { openLink(`#/onJobList?list=onjob&deptsId=${deptsId}&deptsName=${deptsName.replace("、",",")}`); }
                                }
                                >
                                <Icon type="right" size="md" className="roster-arrow" />
                                <div className="depts-warp">
                                    <span className="depts-num">
                                    <span>{ totalEmpNum }</span>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <WhiteSpace size="lg" />
                        {
                            dataAnalysis.map((item, index) => {
                                return (
                                    <div ref={item.type} key={index}>
                                        <div className={`manpower-Report-detail-card ${ item.data.length <= 3 ? "card-smartPie" : ""}`}>
                                            <CardHeader 
                                                title={item.name}
                                                />
                                            {
                                                item.data.length > 3 ?
                                                <SmartStackWS height={342}
                                                    chartData={this.getCharData(item.data)}/>
                                                :
                                                <SmartPie 
                                                    chartData={this.getCharData(item.data)}
                                                    showLegend={true}
                                                />
                                            }
                                        </div>
                                        <WhiteSpace size="lg" />
                                    </div>
                                )
                            })
                        }
                        <HelpModal/>
                        <div className='bottom-attention'>
                            已经到底了
                        </div>
                    </div>
                }
            </div>
        )
    }
}